/******************************************************************************
@file:  Feedback.java
@author Ramesh Anandhan
DESCRIPTION
-----------------------------------------------------------------------------
Copyright (c) 2011, GEEKWAVE SOLUTIONS INC.

All rights reserved.
 ******************************************************************************/
package com.smartc.ui;


import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.smartc.connection.HttpConnection;
import com.smartc.connection.ParsedLoginData;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class Feedback extends Activity implements OnClickListener {

	private static final String TAG = "Feedback";
	private EditText mEditEmail = null;
	private EditText mEditEmp_Id = null;
	private Spinner mEditCity = null;
	private EditText mEditMessage = null;
	private Button mBtnSubmit = null;

	private final int DIALOG_STATUS = 0x01;
	private final int PROGRESS_DLG = 0x04;
	private String mSelectedCity = null;
	private HttpConnection mCityConnection;
	private ResponseHandler mResponse = new ResponseHandler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mCityConnection = new HttpConnection();
		mCityConnection.AddHandler(mResponse);
		setContentView(R.layout.feedback_1);

		mEditEmail = (EditText) findViewById(R.id.feedback_email);
		mEditEmp_Id = (EditText) findViewById(R.id.feedback_eid);
		mEditCity = (Spinner) findViewById(R.id.feedback_city);
		mEditMessage = (EditText) findViewById(R.id.feedback_message);

		mBtnSubmit = (Button) findViewById(R.id.feedback_send);
		mBtnSubmit.setOnClickListener(this);
		
		mEditCity.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (AccountLogin.DEBUG)
					Log.i(TAG, "onItemSelected() position:" + position);

				if (position == 0)
					return;
				mSelectedCity = mResponse.mCity_Id.get(--position);

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});
	}

	@Override
	protected void onStart() {
		super.onStart();
		String domain = getResources().getString(R.string.domain);
		String city_query = getResources().getString(
				R.string.bus_register_city_query);
		String city_url = domain + city_query;
		Log.i(TAG, "onStart city_url:" + city_url);
		mCityConnection.setUrl(city_url);
		mCityConnection.clearParam();
		mCityConnection.Execute();
	}

	public class ResponseHandler extends DefaultHandler {

		//private boolean mMessages = false;
		private boolean mMessage = false;
		private boolean mStatus = false;
		private boolean mCity = false;
		//private boolean mCityMain = false;
		private boolean idCity = false;
		public String mStatusMsg = null;
		public String mMsg = null;
		public ArrayList<String> mCity_List = new ArrayList<String>();
		public ArrayList<String> mCity_Id = new ArrayList<String>();
		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			if (this.mStatus) {
				mStatusMsg = new String(ch, start, length);
			}else if (this.mMessage) {
				mMsg = new String(ch, start, length);
			}else if (this.mCity) {
				mCity_List.add(new String(ch, start, length));
			}else if (this.idCity) {
				mCity_Id.add(new String(ch, start, length));
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {

			if (localName.equals("Messages")) {
				//this.mMessages = false;
				Message myMessage = new Message();
				myMessage.obj = "STATUS";
				handler.sendMessage(myMessage);
			}else if (localName.equals("status")) {
				this.mStatus = false;
			}else if (localName.equals("message")) {
				this.mMessage = false;
			}else if (localName.equals("nmCity")) {
				this.mCity = false;
			}else if (localName.equals("idCity")) {
				this.idCity = false;
			}else if (localName.equals("Cities")) {
				//this.mCityMain = false;
				Message myMessage = new Message();
				myMessage.obj = "CITY";
				handler.sendMessage(myMessage);
			}
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if (localName.equals("Messages")) {
				//this.mMessages = true;
			} else if (localName.equals("status")) {
				this.mStatus = true;
			} else if (localName.equals("message")) {
				this.mMessage = true;
			}else if (localName.equals("nmCity")) {
				this.mCity = true;
			} else if (localName.equals("idCity")) {
				this.idCity = true;
			} else if (localName.equals("Cities")) {
				//this.mCityMain = true;
				mCity_List.clear();
				mCity_Id.clear();
				mCity_List.add("select city");
			}
		}
	}

	private Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage msg:" + (String) msg.obj);
			String loginmsg = (String) msg.obj;
			if (loginmsg.equals("STATUS")) {
				if (mResponse.mStatusMsg.equals("Success")) {
					removeDialog(PROGRESS_DLG);
					showDialog(DIALOG_STATUS);

					mEditEmail.setText("");
					mEditEmp_Id.setText("");
					//mEditCity.setText("");
					mEditMessage.setText("");
				}
			}else if (loginmsg.equals("CITY")) {
				int count = mResponse.mCity_List.size();
				String city[] = new String[count];
				for (int i = 0; i < count; i++)
					city[i] = mResponse.mCity_List.get(i);

				ArrayAdapter Adapter = new ArrayAdapter(Feedback.this,
						R.layout.simple_spinner_item, city);
				mEditCity.setAdapter(Adapter);
			}
		}
	};

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {

		switch (id) {
		case DIALOG_STATUS:
			return new AlertDialog.Builder(Feedback.this).setMessage(
					mResponse.mMsg).setPositiveButton("OK", null).create();
		case PROGRESS_DLG:
			ProgressDialog mDialog = new ProgressDialog(this);
			mDialog.setMessage("Request In progress....");
			mDialog.setIndeterminate(true);
			mDialog.setCancelable(true);
			return mDialog;
		default:
			return super.onCreateDialog(id, args);
		}

	}

	@Override
	public void onClick(View view) {
		int id = view.getId();

		if (id == R.id.feedback_send) {
			String email = mEditEmail.getText().toString().trim();
			
			if(validateInput() == false){
				return;
			}
			
			String employeeId = mEditEmp_Id.getText().toString().trim();
			//String city = mEditCity.getText().toString().trim();
			String Message = mEditMessage.getText().toString().trim();

			String domain = getResources().getString(R.string.domain);
			String query = getResources().getString(R.string.feedback_submit);
			String url = domain + query;
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick city_url:" + url);

			mCityConnection = new HttpConnection();
			mCityConnection.setUrl(url);
			mCityConnection.AddHandler(mResponse);

			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick email:" + email);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick employeeId:" + employeeId);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick city:" + mSelectedCity);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick Message:" + Message);

			// ParsedLoginData.mIdUser = "1";//TO_DO
			mCityConnection.AddParam("idUser", ParsedLoginData.mIdUser);
			mCityConnection.AddParam("idEmail", email);
			mCityConnection.AddParam("nmEmployeeId", employeeId);
			//mCityConnection.AddParam("nmCity", mSelectedCity);
			mCityConnection.AddParam("idCity", mSelectedCity);
			mCityConnection.AddParam("txMessage", Message);

			mCityConnection.Execute();
			showDialog(PROGRESS_DLG);
		}
	}
	
	private boolean validateInput(){
		boolean valid = true;
		String email = mEditEmail.getText().toString().trim();
		String employeeId = mEditEmp_Id.getText().toString().trim();
		//String city = mEditCity.getText().toString().trim();
		String Message = mEditMessage.getText().toString().trim();
		
		Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher matcher = pattern.matcher(email);
		
		if(!(employeeId != null && employeeId.length() > 0)){
			valid = false;
			Toast.makeText(this, "Enter Employee Id", Toast.LENGTH_SHORT).show();
		}
		if(!(Message != null && Message.length() > 0)){
			valid = false;
			Toast.makeText(this, "Enter Message", Toast.LENGTH_SHORT).show();
		}
		if(!(email != null && email.length() > 0)){
			valid = false;
			Toast.makeText(this, "Enter Email", Toast.LENGTH_SHORT).show();
		}
		if(!(mSelectedCity != null && mSelectedCity.length() > 0)){
			valid = false;
			Toast.makeText(this, "Select City", Toast.LENGTH_SHORT).show();
		}
		
		if(!matcher.matches()){
			valid = false;
			Toast.makeText(this, "Enter valid Email Id", Toast.LENGTH_SHORT).show();
		}
		return valid;
	}
}
